/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved. 
 */
"use strict";
const router = require('express').Router();
const request = require('request');
const api = require('../utils/api');
const logger = global.log4js.getLogger('data');
const loginLog = global.log4js.getLogger('login');
var xlsx = require('node-xlsx');
var fs = require('fs');

/**
 * 登录验证
 */
router.use('/login', function (req, res, next) {
    req.session = req.session || {};
    global.tool.send({
        method: req.method,
        uri: api.get('dd3bcbbc5b7e4a06b8118ab44395a21d'),
        json: req.body
    }, function (error, response, body) {
        if (body) {
            if (body.success && body.value) {//登录成功，设置session
                req.session.userData = {
                    userId: body.value.id,
                    userCode: body.value.code,
                    userName: body.value.name,
                    language: req.headers["accept-language"] && req.headers["accept-language"].substr(0, 2),
                    customerId: body.value.customerId,
                    vendorId: body.value.vendorId,
                    logoUrl: body.value.logoUrl,
                    accountType: body.value.type,
                    orgId: body.value.org && body.value.org.id,
                    orgCode: body.value.org && body.value.org.code,
                    orgCategory: body.value.org && body.value.org.category,
                    province: body.value.province,
                    orgName: body.value.org && body.value.org.name,
                    company: [],
                    topCustomer: body.value.topCustomer
                };
                //合并account上的company，必须属于所属组织的company
                let _com = (body.value.org && body.value.org.company.split(',')) || [];
                if (body.value.company) {
                    for (let i = 0; i < _com.length; i++) {
                        if (body.value.company.indexOf(_com[i]) > -1) {
                            req.session.userData.company.push(_com[i]);
                        }
                    }
                } else {
                    req.session.userData.company = _com;
                }
                if (req.session.userData.company.length > 0)
                    req.session.company = req.session.userData.company[0];
                req.session.roleData = body.value.permits || [];
                req.session.roleMap = {
                    index: true
                };
                if (req.session.roleData) {
                    for (let i = 0; i < req.session.roleData.length; i++) {
                        let tmp = req.session.roleData[i].split(':');
                        req.session.roleMap[tmp[1]] = true;
                    }
                }
            }
            res.json(body);
        } else {
            res.json({success: false, msg: '后台服务请求出错'})
        }
    });
});

router.all('*', api.apiAuthentication);

// 该路由使用的中间件
router.use(function timeLog(req, res, next) {
    logger.info('data::' + req.path);
    next();
});

/**
 * 转发请求
 */
router.use('/', function (req, res, next) {
    if (req.header('mySessionCode') && req.header('mySessionCode') !== req.session.userData.userCode) {
        res.json({success: false, code: 417, msg: '登录用户的会话已改变，请刷新页面'});
        return;
    }
    let realUri = pathMapping(req.originalUrl);
    if (!realUri) {
        res.json({success: false, code: 404, msg: 'No api route.'});
        return;
    }
    if (realUri.indexOf('/{') > 0) {
        res.json({success: false, code: 503, msg: 'Api Route Error:存在未替换变量'});
        return;
    }
    req.session.userData = req.session.userData || {};

    if (realUri.indexOf('_download') > 0) {
        /**通过后台导出文件**/
        request.post(realUri, {form: req.body, timeout: 1000 * 60 * 15}).pipe(res);
    } else if (realUri.indexOf('_pagegrid') > 0) {
        /**直接前端导出文件**/
        var data = [];
        var excelName = '无';
        for (var key of Object.keys(req.body)) {
            if ('excelName' != key) {
                var obj = JSON.parse(req.body[key] + "");
                var arr = [];
                for (var idx of Object.keys(obj)) {
                    if ('__id__' != idx) {
                        arr.push(obj[idx]);
                    }
                }
                data.push(arr);
            } else {
                excelName = req.body['excelName'];
            }
        }
        var buffer = xlsx.build([{name: excelName, data: data}]);
        fs.writeFile(__dirname + '/../public/uploadFiles/images/' + excelName + '.xlsx', buffer, 'binary', function () {

            res.set({
                "Content-type": "application/octet-stream",
                "Content-Disposition": "attachment;filename=" + encodeURI(excelName + '.xlsx')
            });
            var fReadStream = fs.createReadStream(__dirname + '/../public/uploadFiles/images/' + excelName + '.xlsx');
            fReadStream.on("data", (chunk) => res.write(chunk, "binary"));
            fReadStream.on("end", function () {
                res.end();
            });
        });

    } else {
        /**
         * 设置发送到后台的对象的公共值
         * @type {*|void}
         */
        let bodyData = global.tool.extend(req.body, {
            createBy: req.session.userData.userCode,
            modifiedBy: req.session.userData.userCode,
            language: req.session.userData.language,
            equipment: global.tool.endTypeEnum[req.session.endType],
            remoteHost: req.get('X-Real-IP') || req.get('x-real-ip') || 'unknown'
        });
        if (req.method === 'POST') {//如果是POST请求，则把后面的?参数放到JSON中去
            if (!bodyData.properties)
                bodyData.properties = {};
            for (let k in req.query) {
                bodyData.properties[k] = req.query[k];
            }
        }
        logger.warn("Real Uri:" + realUri);
        global.tool.send({
            method: req.method,
            uri: realUri,
            json: bodyData
        }, function (error, response, body) {
            if (body)
                res.json(body);
            else
                res.json({success: false, msg: '后台服务请求出错'})
        });
    }
});

/**
 * 根据映射关系，进行地址转换
 * 发送的地址为：/api/uuid@pathv1=v1&pathv2=v2?paramv1=pv1&paramv2=pv2
 *
 * @param path
 */
function pathMapping(path) {
    let sUrl = path.match(/\/api\/([\w-]+)@*([^\?]*)\?*(.*)/),
        uuid = sUrl[1],
        pathVar = sUrl[2],
        paramVar = sUrl[3],
        realUri = api.get(uuid),
        pathVar_ = pathVar.split('&'),
        items,
        regExp;
    if (realUri) {
        for (let i = 0; i < pathVar_.length; i++) {
            items = pathVar_[i].split("=");
            regExp = new RegExp('{' + items[0] + '}');
            realUri = realUri.replace(regExp, items[1]);
        }
        if (paramVar)
            realUri += '?' + paramVar;
    }
    return realUri;
}

module.exports = router;